package torrentfile

import (
	"bytes"
	"crypto/sha1"
	"fmt"
	"github.com/jackpal/bencode-go"
)

type torrent interface {
	fileParser(file []byte) error

	toTorrentFile() (TorrentFile, error)

	writerFile()
}

type metaInfo interface {
	// hash 生成info hash
	hash() ([20]byte, error)

	// splitPieceHashes 切割Pieces
	splitPieceHashes() ([][20]byte, error)
}

// hash 生成info hash
func hash(i interface{}) ([20]byte, error) {
	//  name, size, and piece hashes
	var buf bytes.Buffer
	err := bencode.Marshal(&buf, i)
	if err != nil {
		return [20]byte{}, err
	}

	// info hash，在与跟踪器和对等设备对话时，它唯一地标识文件
	h := sha1.Sum(buf.Bytes())
	return h, nil
}

// splitPieceHashes 切割Pieces
func splitPieceHashes(pieces string) ([][20]byte, error) {
	// SHA-1 hash的长度
	hashLen := 20
	buf := []byte(pieces)

	if len(buf)%hashLen != 0 {
		// 片段的长度不正确
		err := fmt.Errorf("Received malformed pieces of length %d", len(buf))
		return nil, err
	}

	// hash 的总数
	numHashes := len(buf) / hashLen
	hashes := make([][20]byte, numHashes)

	for i := 0; i < numHashes; i++ {
		copy(hashes[i][:], buf[i*hashLen:(i+1)*hashLen])
	}
	return hashes, nil
}
